package cn.uhua.erp.pms.auth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import cn.uhua.erp.pms.auth.service.CustomUserDetailsService;

@EnableWebSecurity
@Configuration
public class CustomSecurityConfig  {

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.csrf(AbstractHttpConfigurer::disable)
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/login", "/css/**", "/js/**", "/images/**").permitAll() // 允许匿名访问的路径
                .anyRequest().authenticated()
            )
            .formLogin(form -> form
                    .loginPage("/login") // 指定登录页面
                    .loginProcessingUrl("/login") // 登录请求处理路径
                    .failureUrl("/login?error") // 自定义登录失败处理逻辑
                    .defaultSuccessUrl("/", true) // 登录成功后跳转到根路径
                    .permitAll() // 允许所有用户访问登录页面
            )
            .logout(logout -> logout
                    .logoutUrl("/logout") // 退出登录URL
                    .logoutSuccessUrl("/login?logout") // 退出成功后跳转的URL
                    .invalidateHttpSession(true) // 使当前HTTP会话失效
                    .deleteCookies("JSESSIONID") // 删除JSESSIONID cookie
            )
            .userDetailsService(customUserDetailsService); // 明确指定使用自定义的UserDetailsService

        return http.build();
    }

    
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }
}
